
function $(selector) {
    return document.querySelector(selector)
}

const terminal = $('#terminal');
const connectBtn = $('#connectBtn');
const closeBtn = $('#closeBtn');
var host = $('#host')
var port = $('#port')
var username = $('#username')
var password = $('#password')
var ws = null

connectBtn.addEventListener('click', () => {
    // https://xtermjs.org/docs/api/terminal/classes/terminal/#cols
    window.term = new Terminal(cols = 1, rows = 1)

    terminal.innerHTML = ''
    term.open(terminal);
    term.focus()
    term.write('websocket connecting...')


    // 连接websocket服务器(ws server)
    ws = new WebSocket(`ws://${window.location.host}/connect/${host.value}?port=${port.value}&username=${username.value}&password=${password.value}`);

    var bufferInput = ''
    // 网页输入的字符，通过websocket发给 ws server服务器。

    term.onKey(e => {
        const key = e.domEvent.key

        const printable =
            !e.domEvent.altKey &&
            !e.domEvent.altGraphKey &&
            !e.domEvent.ctrlKey &&
            !e.domEvent.metaKey;

        if (key === 'Enter') {
            ws.send(bufferInput);
            bufferInput = ''
        } else if (key === 'Backspace') {
            // 用户输入退格键时，删除终端中的最后一个字符
            if (bufferInput.length > 0) {
                bufferInput = bufferInput.slice(0, -1);
                term.write('\b \b');
            }
        } else if (key === 'd' && e.domEvent.ctrlKey) {
            // 用户按下 Ctrl-D
            ws.send('\x04');
            ws.close()
            term.write('close websocket')
        } else if (key === 'l' && e.domEvent.ctrlKey) {
            // 用户按下 Ctrl-L
            term.clear()
            term.focus();
            bufferInput = ''
        } else if (key === 'c' && e.domEvent.ctrlKey) {
            // 用户按下 Ctrl-C
            ws.send('\x03');
        } else if (printable) {
            // 保存多个字符
            bufferInput += key
            // 写一个字符
            term.write(key)
        }

        console.log(`当前的bufferinput ${bufferInput}`)
    });

    term.onData((data) => {
        // 粘贴的情况
        if (data.length > 1) {
            term.write(data);
            bufferInput += data;
        }
    });


    // ws server给的消息，显示到页面
    ws.onmessage = (event) => {
        console.log(event.data, '~~~~~~~ onmessage');
        term.write(event.data)
    };
    term.focus();
    closeBtn.onclick = function (e) {
        ws.close()
        term.clear()
        term.write('断开连接')
    }
});


